#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/components/bk/apis/job/fast_push_file.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
from django import forms
from common.forms import BaseComponentForm, TypeCheckField
from components.component import Component
from common.constants import API_TYPE_OP
from .toolkit import tools, configs

class FastPushFile(Component):
    """
    apiLabel 快速分发文件
    apiMethod POST
    
    ### 功能描述
    
    快速分发文件
    
    ### 请求参数
    
    {{ common_args_desc }}
    
    #### 接口参数
    
    | 字段             |  类型      | 必选   |  描述      |
    |------------------|------------|--------|------------|
    | app_id           |  int       | 是     | 业务ID |
    | file_source      |  array     | 是     | 源文件信息，包含内容见下面参数描述 |
    | file_target_path |  string    | 是     | 目标路径 |
    | ip_list          | array      | 否     | 目标机器，包含内容见下面参数描述 |
    | target_app_id    |  int       | 否     | 目标机器所属业务，全业务需要 |
    | server_set_id    |  int       | 否     | 目标机器分组ID；server_set_id和ip_list至少一个必须存在，如果同时存在，则以server_set_id为准 |
    | account          |  string    | 是     | 目标机器账户名 |
    
    #### file_source
    
    | 字段          |  类型      | 必选   |  描述      |
    |---------------|------------|--------|------------|
    | source_app_id |  int       | 否     | 为源机器所属业务，全业务需要 |
    | file          |  string    | 是     | 源文件路径 |
    | ip_list       |  array     | 否     | IP信息，其中包含ip（源文件服务器IP）和source（IP的子网ID） |
    | server_set_id |  int       | 否     | 源文件服务器分区ID；server_set_id和ip_list至少一个必须存在，如果同时存在，则以server_set_id为准 |
    | account       |  string    | 是     | 源文件服务器账户名 |
    
    #### ip_list
    
    | 字段      |  类型      | 必选   |  描述      |
    |-----------|------------|--------|------------|
    | ip        |  string    | 是     | IP地址 |
    | source    |  int       | 是     | 子网ID |
    
    ### 请求参数示例
    
    ```python
    {
        "app_code": "esb_test",
        "app_secret": "xxx",
        "bk_token": "xxx",
        "app_id": "1",
        "file_source": [
            {
                "server_set_id": "",
                "account": "root",
                "ip_list": [
                    {
                        "ip": "10.0.0.1",
                        "source": 1
                    }
                ],
                "file": "/tmp/tmp.txt"
            }
        ],
        "account": "root",
        "file_target_path": "/tmp",
        "ip_list": [
            {
                "ip": "10.0.0.2",
                "source": 1
            }
        ],
    }
    ```
    
    ### 返回结果示例
    
    ```python
    {
        "result": true,
        "code": "00",
        "message": "",
        "data": {
            "taskInstanceName": "API分发文件1456316951760",
            "taskInstanceId": 10000
        }
    }
    ```
    """
    sys_name = configs.SYSTEM_NAME
    api_type = API_TYPE_OP
    host = configs.host

    class Form(BaseComponentForm):
        app_id = forms.IntegerField(label=u'业务ID', required=True)
        file_source = TypeCheckField(label=u'源文件信息', promise_type=list, required=True)
        file_target_path = forms.CharField(label=u'目标路径', required=True)
        target_app_id = forms.IntegerField(label=u'目标机器所属业务', required=False)
        ip_list = TypeCheckField(label=u'目标机器', promise_type=list, required=False)
        server_set_id = forms.IntegerField(label=u'目标机器分组ID', required=False)
        account = forms.CharField(label=u'目标机器账户名', required=True)

        def clean(self):
            data = self.cleaned_data
            file_source = [ FastPushFile.FileSourceForm(f_s).get_cleaned_data_or_error() for f_s in data['file_source']
                          ]
            ip_list = [ FastPushFile.HostForm(ip).get_cleaned_data_or_error() for ip in data['ip_list']
                      ]
            params = {'applicationId': data['app_id'],
               'fileSource': file_source,
               'fileTargetPath': data['file_target_path'],
               'account': data['account']
               }
            if data['target_app_id'] is not None:
                params.update(targetAppId=data['target_app_id'])
            if data['server_set_id'] is not None:
                params.update(serverSetId=data['server_set_id'])
            else:
                if ip_list:
                    params.update(ipList=ip_list)
                else:
                    raise forms.ValidationError(u'目标机器[ip_list]和目标机器分组ID[server_set_id]至少存在一个。')
            return params

    class FileSourceForm(BaseComponentForm):
        source_app_id = forms.IntegerField(label=u'源机器所属业务', required=False)
        file = forms.CharField(label=u'源文件路径', required=True)
        ip_list = TypeCheckField(label=u'源文件机器', promise_type=list, required=False)
        server_set_id = forms.IntegerField(label=u'源文件机器分区ID', required=False)
        account = forms.CharField(label=u'源文件机器账户名', required=True)

        def clean(self):
            data = self.cleaned_data
            params = {'file': data['file'],
               'account': data['account']
               }
            if data['source_app_id'] is not None:
                params.update(sourceAppId=data['source_app_id'])
            ip_list = [ FastPushFile.HostForm(ip).get_cleaned_data_or_error() for ip in data['ip_list']
                      ]
            if data['server_set_id'] is not None:
                params.update(serverSetId=data['server_set_id'])
            else:
                if ip_list:
                    params.update(ipList=ip_list)
                else:
                    raise forms.ValidationError(u'源文件机器[ip_list]和源文件机器分区ID[server_set_id]至少存在一个。')
            return params

    class HostForm(BaseComponentForm):
        ip = forms.CharField(label=u'IP地址', required=True)
        source = forms.IntegerField(label=u'子网ID', required=True)

        def clean(self):
            data = self.cleaned_data
            return {'ip': data['ip'],
               'source': data['source']
               }

    def handle(self):
        data = self.form_data
        data['starter'] = self.current_user.username
        client = tools.JOBClient(self.outgoing.http_client)
        params = tools.get_basic_json('fastPushFile', params=data)
        result = client.post(self.host, data=params)
        self.response.payload = result
